<template>
  <el-container>
    <el-header>
      <div style="display: flex">
        <logo :height="60" />
        <div class="top-title">欢迎使用组态设计器</div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="300px">
        <tools @on-item-dblclick="onItemDblClick()" />
      </el-aside>
      <el-main>
        <div class="scale-ruler">
          <vue-ruler-tool
            v-model="presetLine"
            :step-length="20"
            :parent="true"
            :is-scale-revise="true"
            :visible.sync="visible"
          >
            <span>test{{ selectedShapeName }}</span>

            <div :class="`scada-canvas scale-${this.zoom}`">
              <v-stage
                ref="stage"
                :config="configKonva"
                @mousedown="handleStageMouseDown"
                @touchstart="handleStageMouseDown"
              >
                <v-layer ref="layer">
                  <v-star
                    v-for="item in list"
                    @transformend="handleTransformEnd"
                    :key="item.id"
                    :config="item"
                  >
                  </v-star>
                  <v-image
                    key="image_1"
                    @transformend="handleTransformEnd"
                    :config="image"
                  />
                  <v-transformer ref="transformer" />
                </v-layer>
              </v-stage>
            </div>
          </vue-ruler-tool>
        </div>
      </el-main>
      <el-aside>
        <prop-editor />
      </el-aside>
    </el-container>
    <el-footer>
      <el-row>
        <el-col :span="2"> 缩放比例 </el-col>
        <el-col :span="3">
          <el-slider v-model="zoom"></el-slider>
        </el-col>
      </el-row>
    </el-footer>
  </el-container>
</template>
<script>

import Konva from 'konva';
import VueRulerTool from '@/components/ruler/vue-ruler-tool'
import Tools from '@/components/tools/Tools'
import Logo from '@/components/logo/Logo';
import PropEditor from '@/components/prop-editor/PropEditor';




const width = 1000;
const height = 600;

export default {
  name: "Design",
  components: {
    'vue-ruler-tool': VueRulerTool,
    Tools,
    Logo,
    PropEditor

  },
  mounted () {
    const image = new window.Image();
    image.src = "https://konvajs.org/assets/yoda.jpg";
    image.onload = () => {
      // set image only when it is loaded
      this.image.image = image;
    };
    for (let n = 0; n < 30; n++) {
      const id = Math.round(Math.random() * 10000).toString();
      const scale = Math.random();
      this.list.push({

        id: id,
        name: id,


        numPoints: 5,
        innerRadius: 30,
        outerRadius: 50, fill: '#89b717',
        opacity: 0.8,
        draggable: true,



        rotation: Math.random() * 180,
        x: Math.random() * width,
        y: Math.random() * height,



        // width: 100,
        // height: 100,
        scaleX: scale,
        scaleY: scale,


        shadowColor: 'black',
        shadowBlur: 10,
        shadowOffsetX: 5,
        shadowOffsetY: 5,
        shadowOpacity: 0.6,


      }
      );
    }
  },
  data () {
    return {
      image: {

        id: 'image_1',
        name: 'image_1',

        image: null,
        numPoints: 5,
        innerRadius: 30,
        outerRadius: 50, fill: '#89b717',
        opacity: 0.8,
        draggable: true,



        rotation: 0,
        x: Math.random() * width,
        y: Math.random() * height,



        // width: 100,
        // height: 100,
        scaleX: 1,
        scaleY: 1,


        shadowColor: 'black',
        shadowBlur: 10,
        shadowOffsetX: 5,
        shadowOffsetY: 5,
        shadowOpacity: 0.6,


      },
      selectedShapeName: '',
      list: [],
      dragItemId: null,
      configKonva: {
        width: width,
        height: height
      },
      presetLine: [{ type: 'h', site: 200 }, { type: 'v', site: 100 }],
      visible: true,

      zoom: 100,
    };
  },
  methods: {
    handleTransformEnd (e) {
      // shape is transformed, let us save new attrs back to the node
      // find element in our state
      const rect = this.list.find(
        (r) => r.name === this.selectedShapeName
      );
      // update the state
      rect.x = e.target.x();
      rect.y = e.target.y();
      rect.rotation = e.target.rotation();
      rect.scaleX = e.target.scaleX();
      rect.scaleY = e.target.scaleY();

      // change fill
      rect.fill = Konva.Util.getRandomColor();
    },
    handleStageMouseDown (e) {
      // clicked on stage - clear selection
      if (e.target === e.target.getStage()) {
        this.selectedShapeName = '';
        this.updateTransformer();
        return;
      }

      // clicked on transformer - do nothing
      const clickedOnTransformer =
        e.target.getParent().className === 'Transformer';
      if (clickedOnTransformer) {
        return;
      }

      // find clicked rect by its name
      const name = e.target.name();
      const rect = this.list.find((r) => r.name === name);
      if (rect) {
        this.selectedShapeName = name;
      } else {
        this.selectedShapeName = '';
      }
      this.updateTransformer();
    },
    updateTransformer () {
      // here we need to manually attach or detach Transformer node
      const transformerNode = this.$refs.transformer.getNode();
      const stage = transformerNode.getStage();
      const { selectedShapeName } = this;

      const selectedNode = stage.findOne('.' + selectedShapeName);
      // do nothing if selected node is already attached
      if (selectedNode === transformerNode.node()) {
        return;
      }

      if (selectedNode) {
        // attach to another node
        transformerNode.nodes([selectedNode]);
      } else {
        // remove transformer
        transformerNode.nodes([]);
      }
    },
    addToCanvas () {
      console.log('添加图片到画布');
      console.log(JSON.stringify(this.$refs['fabric-canvas'].canvas), 'fabric model');
    },
    onItemDblClick () {

    }
    // handleDragstart (e) {
    //   // save drag element:
    //   this.dragItemId = e.target.id();
    //   // move current element to the top:
    //   const item = this.list.find(i => i.id === this.dragItemId);
    //   const index = this.list.indexOf(item);
    //   this.list.splice(index, 1);
    //   this.list.push(item);
    // },
    // // eslint-disable-next-line no-unused-vars
    // handleDragend (e) {
    //   this.dragItemId = null;
    // }
  },
  watch: {
    visible (val) {
      console.log(val)
    }
  }
};
</script>

<style lang="scss" scoped>
.top-title {
  height: 60px;
  line-height: 60px;
  margin-left: 50px;
  font-size: 20px;
  font-weight: bold;
}

.el-container {
  height: 100%;
}

.el-header {
  height: 50px;
  border-bottom: 1px solid #cccccc;
}
.el-aside {
  border-right: 1px solid #cccccc;
}
.el-footer {
  height: 30px;
  border-top: 1px solid #cccccc;
}

.el-main {
  background-color: #bbb;
}

.scale-ruler {
  width: 100%;
  height: 100%;
}

.scada-canvas {
  margin: 10px;
  background-color: #fff;
  border: 1px solid #999;
  position: relative;
  box-shadow: 1px 1px 5px #999;

  transform-origin: left top;
  width: 1000px;
  height: 600px;
  background: rgb(255, 255, 255);

  background: #fff
    url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%202%202%22%3E%3Cpath%20d%3D%22M1%202V0h1v1H0v1z%22%20fill-opacity%3D%22.05%22%2F%3E%3C%2Fsvg%3E") !important;
  background-size: 16px 16px !important;
  transition: background-color 0.2s ease-in-out;
}
</style>
<style lang="scss" scoped>
@use "sass:math";
/*缩放处理*/
@for $i from 0 through 100 {
  .scale-#{$i} {
    transform: scale(math.div($i, 100));
  }
}
</style>